package io.renren.modules.fileserver.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.R;
import io.renren.common.utils.SpringContextUtils;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.systemconfig.dao.SysConfigServerDao;
import io.renren.modules.systemconfig.entity.SystemConfigServersEntity;
import io.renren.ssh.SFTPClient;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;



@RestController
@RequestMapping("fileservice")
public class FileController extends AbstractController {
	@Autowired
	private SpringContextUtils springContextUtils;

	@Autowired
	private SysConfigServerDao serverMapper;

	@Value("${spring.web.upload-path}")
	private String basepath;
	
	@RequestMapping("/uploadAvatar")
	@ResponseBody
	public R handleFileUpload(@RequestParam("file") MultipartFile file) throws NoSuchAlgorithmException, IOException {
		
		String destFileName =  basepath+"/cover" + File.separator + getUser().getUserId()+".jpg";
		File destFile = new File(destFileName);
        destFile.getParentFile().mkdirs();
        file.transferTo(destFile);
		return R.ok();
	}
	
	/**
	 * 获取文件片信息
	 * 
	 * @param id
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	@GetMapping("getAvatar/{id}")
	@ResponseBody
	public ResponseEntity<Object> getAvatar(@PathVariable long id) throws UnsupportedEncodingException {

		String destFileName =  basepath+"/cover" + File.separator + id+".jpg";
		System.out.println(destFileName);
		try {
            return ResponseEntity.ok(springContextUtils.getResource("file:" + destFileName));
        } catch (Exception e) {
        	return ResponseEntity.ok(springContextUtils.getResource("file:" + basepath+"/cover" + File.separator + "default.jpg"));
        }
	}

	@GetMapping("downloadsftpfile/{serverId}/{path}")
	@ResponseBody
	public ResponseEntity<byte[]> downloadsftpfile(@PathVariable String path,@PathVariable long serverId) throws UnsupportedEncodingException {
		HttpHeaders headers = new HttpHeaders();// 设置响应头
		HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
		headers.add("Content-Disposition", "attachment;filename=temp");
		try {
			SystemConfigServersEntity serverInfo = serverMapper.selectById(serverId);
			System.out.println(JSONObject.toJSONString(serverInfo));
			SFTPClient sftp = new SFTPClient(serverInfo);
			String  depath = new String(Base64.getDecoder().decode(path),StandardCharsets.UTF_8);
			System.out.println(depath);
			byte[] bytes = sftp.getFile(depath);
			sftp.close();


			return new ResponseEntity<byte[]>(bytes, headers, statusCode);
			} catch (Exception e) {
				return new ResponseEntity<byte[]>("".getBytes(StandardCharsets.UTF_8), headers, statusCode);
			}

	}


	@GetMapping("getFile/{id}")
	@ResponseBody
	public ResponseEntity<byte[]> getFile(@PathVariable String id,HttpServletRequest req,HttpServletResponse response) throws UnsupportedEncodingException {
		String destFileName=basepath + File.separator+"file" + File.separator + id;
		 response.setContentType("image/jpeg");//设置输出流内容格式为图片格式
	     response.setCharacterEncoding("utf-8");//response的响应的编码方式为utf-8
	     InputStream in = null;
		 try {
			 in = new FileInputStream(new File(destFileName));
         
         	byte[] body = null;
 		  	body = new byte[in.available()];
 		  	in.read(body);
     		String fileName = id;
	   		HttpHeaders headers = new HttpHeaders();// 设置响应头
	   		headers.add("Content-Disposition", "attachment;filename=" + fileName);
	   		HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
	   		ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(body, headers, statusCode);
	   		return result;
	      } catch (IOException e) {
             e.printStackTrace();
             return null;
         }finally{
        	 if(in !=null ) {
        		 try {in.close();} catch (Exception e2) {}
        	 }
         }
	}
	
	@RequestMapping("/uploadSmallImg")
	@ResponseBody
	public R uploadSmallImg(@RequestParam("file") MultipartFile file,HttpServletRequest req) throws NoSuchAlgorithmException, IOException {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String destFileName =  basepath+"/cover" + File.separator + uuid+".jpg";
		File destFile = new File(destFileName);
        destFile.getParentFile().mkdirs();
        file.transferTo(destFile);
		return R.ok().put("url",uuid);
	}
	@RequestMapping("/sftpuploadfile")
	@ResponseBody
	public R sftpuploadfile(MultipartFile file,HttpServletRequest req) throws IllegalStateException, IOException {
		try{
			String path=req.getParameter("pwd");
			Long serverId = Long.parseLong(req.getParameter("serverId"));
			System.out.println(path+"  "+serverId);
			SystemConfigServersEntity serverInfo = serverMapper.selectById(serverId);
			SFTPClient sftp = new SFTPClient(serverInfo);
			sftp.upload( path,file.getOriginalFilename(),file.getInputStream());
			sftp.close();
			return R.ok();
		}catch (Exception e){
			e.printStackTrace();
			return R.error("上传失败!");
		}

	}
	@RequestMapping("/uploadfile")
	@ResponseBody
	public R uploadFile(MultipartFile file,HttpServletRequest req) throws IllegalStateException, IOException {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		String destFileName=basepath + File.separator+"file" + File.separator + uuid;
		File uploadFile=new File(destFileName);
		file.transferTo(uploadFile);

		return R.ok().put("url", uuid);
	}
	@RequestMapping("/uploadVsersion")
	@ResponseBody
	public R uploadApk(MultipartFile file,HttpServletRequest req) throws IllegalStateException, IOException {


		return R.ok();
	}
	
	@GetMapping("getAPK/{id}")
	@ResponseBody
	public ResponseEntity<Object> getAPKr(@PathVariable long id) throws UnsupportedEncodingException {

		String destFileName =  basepath+"/cover" + File.separator + id+".apk";
		System.out.println(destFileName);
		try {
            return ResponseEntity.ok(springContextUtils.getResource("file:" + destFileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
	}
	

	@GetMapping("getImg/{id}")
	public ResponseEntity<byte[]> getImg(@PathVariable String id,HttpServletRequest req,HttpServletResponse response) throws UnsupportedEncodingException, FileNotFoundException {
		String destFileName=basepath + File.separator+"cover" + File.separator + id;
		 response.setContentType("image/jpeg");//设置输出流内容格式为图片格式
	     response.setCharacterEncoding("utf-8");//response的响应的编码方式为utf-8
	     InputStream in = null;
		 try {
          	in = new FileInputStream(new File(destFileName));
          
          	byte[] body = null;
  		  	body = new byte[in.available()];
  		  	in.read(body);
      		String fileName = id+".jpg";
    		HttpHeaders headers = new HttpHeaders();// 设置响应头
    		headers.add("Content-Disposition", "attachment;filename=" + fileName);
    		HttpStatus statusCode = HttpStatus.OK;// 设置响应吗
    		ResponseEntity<byte[]> result = new ResponseEntity<byte[]>(body, headers, statusCode);
    		return result;
	      } catch (IOException e) {
              e.printStackTrace();
              return null;
          }finally{
        	 if(in !=null ) {
        		 try {in.close();} catch (Exception e2) {}
        	 }
         }
	}
	@GetMapping("pay/rqcode/{id}")
	@ResponseBody
	public ResponseEntity<Object> getQrCodeImg(@PathVariable String id,HttpServletRequest req) throws UnsupportedEncodingException, FileNotFoundException {
		
		String destFileName= basepath+"/qrcode" + File.separator + id+".png";
		System.out.println(destFileName);
		try {
            return ResponseEntity.ok(springContextUtils.getResource("file:" + destFileName));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
	}
	
	@RequestMapping("/batchUpload")
	@ResponseBody
	public R batchUpload(MultipartFile file,HttpServletRequest req) throws IllegalStateException, IOException {
		String ts=req.getParameter("ts");
		String path=basepath + File.separator+ts + File.separator ;
		File p=new File(path);
		if(!p.exists()) {
			p.mkdirs();
		}
		String destFileName=path+ file.getOriginalFilename();
		File uploadFile=new File(destFileName);
		file.transferTo(uploadFile);
		return R.ok().put("url",file.getOriginalFilename()); 
	}
}
